package cn.senjoeson.demo.servlet;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.senjoeson.demo.bean.User;
import cn.senjoeson.demo.dao.UserDao;
import cn.senjoeson.demo.utils.MessageUtils;
import cn.senjoeson.demo.utils.TextUtils;

public class Register extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("register访问已经到达");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
            MessageUtils.sendMessage("register.jsp",request, response, "用户名密码不能为空!");
            return;
        }
        if (!password.equals(confirmPassword)) {
            MessageUtils.sendMessage("register.jsp",request, response, "两次密码输入不一致");
            return;
        }
        UserDao userDao = new UserDao();
        User userDaoByName = userDao.findByName(username);
        if (userDaoByName.getUsername() == null) {
            System.out.println("该用户不存在");
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setRole("普通用户");
            user.setCreateDate(new Date().toString());
            user.setUpdateDate(new Date().toString());
            MessageUtils.sendMessage("index.jsp",request,response,"注册成功!请登录");

        } else {
            MessageUtils.sendMessage("register.jsp",request, response, "已经存在该用户名");
            return;
        }


    }
}
